//
//  MessageTimeContent.swift
//  YBIMKit
//
//  Created by Shang Hai Rui Xi on 2019/1/2.
//  Copyright © 2019 Shanghai Three-Cobbler Technology Service Co.Ltd. All rights reserved.
//

import UIKit

public class MessageTimeContent: MessageContentable {
    
    public static var viewType: MessageContentViewable.Type {
        return MessageImageContentView.self
    }
    public weak var delegate: MessageDelegate?
    public var layoutMargins: UIEdgeInsets = UIEdgeInsets.zero
    public func sizeThatFits() -> CGSize {
        return .zero
    }
    // 这个是比较耗时的操作，所以这里设置为全局只创建一次
    static let defaultFormat = DateFormatter.dateFormat(fromTemplate: "hh:mm", options: 0, locale: nil) ?? "hh:mm"
    
    public var date: Date
    public var text: String {
        return MessageTimeContent.dd(date)
    }
    
    public init(date: Date) {
        self.date = date
    }
    
    static func dd(_ date: Date) -> String {
        // yy-MM-dd hh:mm
        // MM-dd hh:mm
        // 星期一 hh:mm - 7 * 24小时内
        // 昨天 hh:mm - 2 * 24小时内
        // 今天 hh:mm - 24小时内
        let s1 = TimeInterval(date.timeIntervalSince1970)
        let s2 = TimeInterval(time(nil))
        
        let dz = TimeInterval(TimeZone.current.secondsFromGMT())
        
        let formatter = DateFormatter()
        // 每次都创建会非常耗时
        let format = MessageTimeContent.defaultFormat
        
        let days1 = Int64(s1 + dz) / (24 * 60 * 60)
        let days2 = Int64(s2 + dz) / (24 * 60 * 60)
        
        switch days1 - days2 {
        case +0:
            // Today
            formatter.dateFormat = "\(format)"
        case +1:
            // Tomorrow
            formatter.dateFormat = "'明天' \(format)"
        case +2 ... +7:
            // 2 - 7 day later
            formatter.dateFormat = "EEEE \(format)"
        case -1:
            formatter.dateFormat = "'昨天' \(format)"
        case -2:
            formatter.dateFormat = "'前天' \(format)"
        case -7 ... -2:
            // 2 - 7 day ago
            formatter.dateFormat = "EEEE \(format)"
        default:
            // Distant
            if date.isThisYear() {
                formatter.dateFormat = "MM-dd \(format)"
            } else {
                formatter.dateFormat = "yy-MM-dd \(format)"
            }
        }
        return formatter.string(from: date)
    }
}


extension Date {
    func isThisYear() -> Bool {
        let calendar = NSCalendar.current
        let year1 = calendar.component(.year, from: Date())
        let year2 = calendar.component(.year, from: self)
        return year1 == year2
    }
}
